(function( $ ) {
  $.widget( "unu.unugrid", {
    // These options will be used as defaults
    options: { 
		clear: null,
		rowdata : null,
		data : {rows : 20, page : 1},
		noPage : false,
		selectrow : function(){
			return false;
		},
		editClick : function(){
			return false;
		},
		deleteClick : function(){
			return false;
		},
		detailClick : function(){
			return false;
		},
		customClick : function(){
			return false;
		},
		selectedId : null
    },
	selectedId : function (){
		return this.options.selectedId;
	},
	getRowData : function (id){
		if (id == null)
			return this.options;
		else
			return this.options.rowdata[id];
	},
	defaultColumn : {
		label : "",
		index : "id"
	},
	setData : function (data){
		this.options.data = $.extend(this.options.data, data);
		return data;
	},
	
	refresh : function(){
		var el = $(this.element);
		el.html("");
		this._create();
	},
	
    // Set up the widget
    _create: function() {
		var self = this
		var el = $(this.element);
		table = $("<table id='table_"+el.attr("id")+"' class='table  table-striped table-bordered table-advance flip-content table-hover'><thead class='flip-content' id='thead_"+el.attr("id")+"'><tr id='tr_first_"+el.attr("id")+"' ></tr></thead></table>");
		table.appendTo(el);
		header = table.find("tr");
		// console.log(this.options.column[0]);
		collen = 0;
		for(i=0; i < this.options.column.length; i++){
			// console.log(this.options.column[i]);
			var column = this.options.column[i];
			column = $.extend(this.defaultColumn,column);
			header.append("<th  id='td_"+i+el.attr("id")+"'>"+column.label+"</th>");
			collen++;
		}
		table.append("<tbody id='tbody_"+el.attr("id")+"'><tr><th colspan='"+collen+"'>Loading data ..</th></tr></tbody>");
		// table.append("<tfoot class='paging'><tr><th colspan='"+collen+"'></th></tr></tfoot>");
		this.table = table;
		$.ajax({
			url : this.options.url,
			data :  this.options.data,
			type : 'POST',
			dataType : 'JSON'
		}).done(function(response){
		//	console.log(self.table);
			self.table.find("tbody#tbody_"+el.attr("id")).html("");
			var rows = response.rows;
			self.options.rowdata = rows;
			for(i=0; i < rows.length; i++){
				var tr = $("<tr id='tr_"+i+el.attr("id")+"' class='gridrow' data-id='"+i+"'></tr>");
				
				for(j=0; j < self.options.column.length; j++){
					var column = self.options.column[j];
					if (rows[i][column.index] == null){
						value = '<td></td>';
					}else{
						value = '<td>'+rows[i][column.index]+'</td>';
					}
					if (typeof column.type != "undefined"){
						if( column.type == "action"){
							value = '<td><a href="#" class="btn btnEdit default btn-xs green" data-id='+rows[i][column.index]+' data-seq='+i+'><i class="icon-edit"></i> Edit</a> &nbsp; ' +
							'<a href="#" class="btn btnDelete default btn-xs red" data-id='+rows[i][column.index]+' data-seq='+i+'><i class="icon-trash"></i> Delete</a></td>';
						}else if( column.type == "assign"){
							if (rows[i][column.index] == null){
								value = '<td><a href="#" class="btn btnCustom default btn-xs blue" data-wo_number='+rows[i][column.index1]+'  data-task_number='+rows[i][column.index2]+' data-id='+rows[i][column.index]+' data-seq='+i+'><i class="icon-plus"></i> Assign</a> &nbsp; ' +
							'</td>';
							}else{
								value = '<td><a href="#" class="btn btnEdit default btn-xs green" data-id='+rows[i][column.index]+' data-seq='+i+'><i class="icon-edit"></i> Edit</a> &nbsp; ' +
							'<a href="#" class="btn btnDelete default btn-xs red" data-id='+rows[i][column.index]+' data-seq='+i+'><i class="icon-trash"></i> Delete</a></td>';
							}
	 						  
						}else if( column.type == "detail"){
							value = '<td><a href="#" class="btn btnDetail default btn-xs blue" data-id='+rows[i][column.index]+' data-seq='+i+'><i class="icon-list"></i> Detail</a></td>';
						}else if( column.type == "rowdetail"){
							value = '<td style="width:30px" data-url="'+column.url+'" data-task="'+column.task+'" data-id="'+rows[i][column.index]+'" class="rowdetail" ><span class="icon-plus" ></span></td>';
							$(value).data(column.data);
						}else if( column.type == "custom"){
							value = '<td><a href="#" class="btn btnCustom default btn-xs" data-id='+rows[i][column.index]+' data-seq='+i+'><i class="icon-list"></i> '+column.btnLabel+'</a></td>';
						}else if( column.type == "currency"){
                            value = '<td class="currency">'+rows[i][column.index]+'</td>';
						}
					}
					tr.append(value);
				}
				self.table.find("tbody").append(tr);
			}
			var gridrow = self.table.find(".gridrow");
			gridrow.click(function(){
				// gridrow.removeClass("active");
				data = $(this).data();
				self.options.selectedId = data.id;
				// $(this).addClass("active");
				self.options.selectrow();
			});
			$(".currency").formatCurrency();
			/* paging */
			if ( ! self.options.noPage ){
			var paging = '<center  ><ul class="pagination"><li class="pagenumberback"><a href="#">&laquo;</a></li>'
			
			var total = response.total;
			var page = response.page;
			if (total > 10)
				pageall = 10
			else
				pageall = total
			
			for(i=1; i <= pageall; i++){
				if (i == page)
					paging += "<li class='active pagenumber' ><a  style='cursor:pointer'  >"+i+"</a></li>";
				else					
					paging += "<li class='pagenumber' ><a  style='cursor:pointer' >"+i+"</a></li>";
			}
			
			if (total > 10)
				paging += '<li><a href="#">...</a></li>';
			
			paging += '<li><a href="#"  class="pagenumbernext">&raquo;</a></li></ul><center>';
			
			$(paging).appendTo(el);
			var pagenumber = $(".pagenumber");
			pagenumber.click(function(){
				pagenumber.removeClass("active");
				$(this).addClass("active");
				self.options.data.page = $(this).find("a").text();
				self.refresh();
			});
			
			pagenumberback = $(".pagenumberback");
			pagenumberback.click(function(){
				
				$(".pagenumber.active").prev().addClass("active");
				pagenumber.removeClass("active");
				self.options.data.page = $(".pagenumber.active").text() - 1;
				self.refresh();
			});
			
			pagenumbernext = $(".pagenumbernext");
			pagenumbernext.click(function(){
				
				$(".pagenumber.active").next().addClass("active");
				pagenumber.removeClass("active");
				self.options.data.page = $(".pagenumber.active").text() + 1;
				self.refresh();
			});
			}
			/* event */
			
			$(".rowdetail").click(function(){
				isClose = $(this).find("span").hasClass("icon-plus");
				$(".detail-body").remove();
				if (isClose){
					$(".rowdetail").find("span").addClass("icon-plus");
					$(".rowdetail").find("span").removeClass("icon-minus");
					$(this).find("span").removeClass("icon-plus");
					$(this).find("span").addClass("icon-minus");
					data  = $(this).data();
					thistr =  $(this).parent();
					$.ajax({
						url : data.url,
						data : { task : data.task , id  : data.id},
						type : 'POST'
					}).done(function(response){
						$( "<tr class='detail-body'><td colspan='"+collen+"'>"+response+"</td></tr>" ).insertAfter(thistr);
					});
				}else{
					$(this).find("span").removeClass("icon-minus");
					$(this).find("span").addClass("icon-plus");
				}
			});
			
			$(".btnEdit").click(function(){
				var data = $(this).data();
				var id = data.id;
				var seq = data.seq;
				var row = self.options.rowdata;
				self.options.editClick(id,row[seq],row);
			});
			
			$(".btnDelete").click(function(){
				var data = $(this).data();
				var id = data.id;
				var seq = data.seq;
				var row = self.options.rowdata;
				self.options.deleteClick(id,row[seq],row);
			});
			
			$(".btnDetail").click(function(){
				var data = $(this).data();
				var id = data.id;
				var seq = data.seq;
				var row = self.options.rowdata;
				self.options.detailClick(id,row[seq],row);
			});
			
			$(".btnCustom").click(function(){
				var data = $(this).data();
				var id = data.id;
				var seq = data.seq;
				var row = self.options.rowdata;
				self.options.customClick(id,row[seq],row);
			});
			
			$(".btnAssign").click(function(){
				var data = $(this).data();
				var id = data.id;
				var wo_number = data.wo_number;
				var task_number = data.task_number
				var seq = data.seq;
				var row = self.options.rowdata;
				self.options.customClick(id,wo_number,task_number);
			});
		});
    },
	
    // Use the _setOption method to respond to changes to options
    _setOption: function( key, value ) {
      switch( key ) {
        case "clear":
          // handle changes to clear option
          break;
      }
 
      // In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget
      $.Widget.prototype._setOption.apply( this, arguments );
      // In jQuery UI 1.9 and above, you use the _super method instead
      this._super( "_setOption", key, value );
    },
 
    // Use the destroy method to clean up any modifications your widget has made to the DOM
    destroy: function() {
      // In jQuery UI 1.8, you must invoke the destroy method from the base widget
      $.Widget.prototype.destroy.call( this );
      // In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
    }
  });
}( jQuery ) );